package com.app.module.camera.core.observer

import android.content.Context
import android.media.MediaRecorder
import android.net.Uri
import android.opengl.EGLSurface
import android.util.Log
import android.util.SparseIntArray
import android.view.Surface
import com.app.module.camera.core.FrameBean
import com.app.module.camera.ext.runOnUIThread
import com.app.module.camera.ext.windowManager
import com.app.module.camera.utils.FileUtils
import java.io.File
import java.sql.Timestamp


class VideoCapturer(context: Context) : FramePreviewer(context) {

    private val DEFAULT_ORIENTATIONS = SparseIntArray(4).apply {
        append(Surface.ROTATION_0, 0)
        append(Surface.ROTATION_90, 90)
        append(Surface.ROTATION_180, 180)
        append(Surface.ROTATION_270, 270)
    }

    private val INVERSE_ORIENTATIONS = SparseIntArray(4).apply {
        append(Surface.ROTATION_0, 0)
        append(Surface.ROTATION_90, 90)
        append(Surface.ROTATION_180, 180)
        append(Surface.ROTATION_270, 270)
    }

    private var mMediaRecorder: MediaRecorder? = null
    private var startTime : Timestamp ?= null

    init {
        mMediaRecorder = MediaRecorder()
    }


    fun open(sensorOrientation : Int){
        val fromFile = Uri.fromFile(File(FileUtils.getPath(false)))
        val fileDescriptor = mContext.contentResolver.openFileDescriptor(fromFile, "w")!!.fileDescriptor
        val rotation = mContext.windowManager.defaultDisplay.rotation
        Log.e("VideoCapturer","open  sensorOrientation=${sensorOrientation}   rotation=$rotation")
        mMediaRecorder?.apply {
            setAudioSource(MediaRecorder.AudioSource.MIC)
            setVideoSource(MediaRecorder.VideoSource.SURFACE)
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
            setOutputFile(fileDescriptor)
            setVideoEncodingBitRate(900 * 1024)
            setVideoFrameRate(30)
            setVideoSize(getWidth(), getHeight())
            setVideoEncoder(MediaRecorder.VideoEncoder.H264)
            setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
            when (sensorOrientation) {
                90 -> setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation))
                270 -> setOrientationHint(INVERSE_ORIENTATIONS.get(rotation))
            }
            prepare()
            super.setSurface(this.surface)
            super.open()
            mMediaRecorder?.start()
        }
    }

    override fun close() {
        super.close()
        try {
            Log.e("VideoCapturer"," 结束录制 ${Timestamp(System.currentTimeMillis())}")
            mMediaRecorder?.stop()
            mMediaRecorder?.reset()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("VideoCapturer" , "close() ${e.localizedMessage} ")
        }
    }

    override fun recycle() {
        super.recycle()
        mMediaRecorder?.release()
        mMediaRecorder = null
    }

    override fun finishDraw(surface: EGLSurface?, bean: FrameBean) {
        super.finishDraw(surface, bean)
        if(startTime == null){
            startTime = Timestamp(bean.timeStamp)
            Log.e("VideoCapturer"," 开始录制 $startTime")
            mContext.runOnUIThread {
                try {
                    mMediaRecorder?.start()
                } catch (e: Exception) {
                    e.printStackTrace()
                    Log.e("VideoCapturer" , "close() ${e.localizedMessage} ")
                }
            }
        }
    }

    override fun setSurface(Surface: Surface) {
    }

    override fun open() {
    }
}
